/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   04.05.2010
 * @version SVN: $Id: ScannedBarcodesForm.java 155 2010-05-19 13:51:47Z f.aarndt@web.de $
 */

package org.cakis.client.forms;

import javax.microedition.lcdui.List;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

import org.cakis.client.CakisMIDlet;
import org.cakis.client.commands.ResumeCommand;
import org.cakis.client.commands.SelectScannedProductCommand;

/**
 * ScannedBarcodesForm
 *
 * @author Florian Arndt
 */
public class ScannedBarcodesForm extends AbstractList {
	private static int recordCount;
	private CakisMIDlet m;

	public ScannedBarcodesForm (CakisMIDlet m) {
		super("Offline Barcodes:", List.EXCLUSIVE, m);
		recordCount = 0;
		this.m = m;
		
		this.addCommand(new SelectScannedProductCommand(m, this));
		this.addCommand(new ResumeCommand(m));
	}
	
	public void run() {		
		RecordStore barcodeStore = null;
		try {
			this.deleteAll();
			//RecordStore.deleteRecordStore("barcodeStore");
			barcodeStore = RecordStore.openRecordStore("barcodeStore", false);
			for (int i = 0; i < barcodeStore.getNumRecords(); i++) {
				this.append(new String(barcodeStore.
						getRecord(recordCount+i+1)).trim(), null);
			}
			System.out.println(barcodeStore.getNumRecords());
			barcodeStore.closeRecordStore();
			m.display(this);
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
		} catch (RecordStoreNotFoundException e) {
			m.handleResumeCommand();
		} catch (RecordStoreException e) {
			try {
				barcodeStore.closeRecordStore();
				RecordStore.deleteRecordStore("barcodeStore");
			} catch (Exception e1) {
				e1.printStackTrace();
			} 
			m.handleResumeCommand();
		}
	}
	
	public String getSelectedProductString() {
		return this.getString(this.getSelectedIndex());
	}

	public static int getRecordCount() {
		return recordCount;
	}

	public static void setRecordCount() {
		ScannedBarcodesForm.recordCount += 1;
	}
}
